/**
 * Created by IntelliJ IDEA.
 * User: dinesh
 * Date: Apr 14, 2012
 * Time: 4:14:41 PM
 * To change this template use File | Settings | File Templates.
 */
/**
 * Created by IntelliJ IDEA.
 * User: dinesh
 * Date: Mar 31, 2012
 * Time: 8:29:44 PM
 * To change this template use File | Settings | File Templates.
 */
/***************************/

  //global vars
	var form = $("#frmData");
	var fullName = $("#fullName");
	var nameInfo = $("#fullNameInfo");
	var email = $("#email");
	var emailInfo = $("#emailInfo");
    var sectionInfo =$("#sectionInfo");
    var instituteInfo =$("#instituteInfo");
    var section_id =$("#section_id");
   // var epfNo = $("#epfNo");
   // var epfNoInfo = $("#epfNoInfo");
    var nic = $("#nic");
    var nicInfo = $("#nicInfo");
    var uid = $("#id");


    var isEdit = false;

$(document).ready(function(){
	fullName.blur(validateName);
	email.blur(validateEmail);
	fullName.keyup(validateName);
    nic.blur(validateNic);

    disableForm("frmData");
} );
//validation functions
function validateSection(){
		var instituteValue = $('#institute_id :selected').val();
		if(instituteValue==0){
			//section_id.addClass("errorField");
			instituteInfo.text("Please setect the employ Institute ");
			instituteInfo.addClass("errorField");
			return false;
		}else{
            instituteInfo.text(" ");
			instituteInfo.removeClass("errorField");
            return true;
        }
	}
	function validateEmail(){
		var a = $("#email").val();
		var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
		if(filter.test(a)){
			email.removeClass("errorField");
			emailInfo.text("");
			emailInfo.removeClass("errorField");
			return true;
		}
		//if it's NOT valid
		else{
			email.addClass("errorField");
			emailInfo.text("Type a valid e-mail please ");
			emailInfo.addClass("errorField");
			return false;
		}
	}
	function validateName(){
		if(fullName.val().length < 5){
			fullName.addClass("errorField");
			nameInfo.text("We want names with more than 3 letters!");
			nameInfo.addClass("errorField");
			return false;
		}
		else{
			fullName.removeClass("errorField");
			nameInfo.text("");
			nameInfo.removeClass("errorField");
			return true;
		}
	}

function validateNic(fn){
        var reg = /^[0-9]{9}[vVxX]$/;
        if (reg.test(nic.val())) {
            //test with db
            var params =encodeURIComponent("nic") + "="+nic.val()+"&" + encodeURIComponent("id") + "="+uid.val();
            ajaxPost("?employee/checkNic", params, function(data) {
			var response =JSON.parse(data);
			if (response.status==false) {
				return;
			}
             if(response.message){
                nic.removeClass("errorField");
		        nicInfo.text("");
			    nicInfo.removeClass("errorField");
                if (typeof fn === 'function') {
                    fn();
                }
			    return true;
             }else{
                nic.addClass("errorField");
			    nicInfo.text("NIC alredy exist !");
			    nicInfo.addClass("errorField");
			    return false;
             }
		});

        }else{
            nic.addClass("errorField");
			nicInfo.text("Please enter valid NIC number");
			nicInfo.addClass("errorField");
			return false;
        }		
	}


  function clearValidate(){
        email.removeClass("errorField");
		emailInfo.text("");
		emailInfo.removeClass("errorField");
        fullName.removeClass("errorField");
        nameInfo.text("");
        nameInfo.removeClass("errorField");
        sectionInfo.text("");
        sectionInfo.removeClass("errorField");
        nic.removeClass("errorField");
		nicInfo.text("");
        instituteInfo.removeClass("errorField");
		instituteInfo.text("");
  }

//////page data  ////
var isNew = false;

//////////// data Grid /////////
var mygrid;
var timeoutHnd;
var flAuto = false;
function gridGenerator() {
    mygrid = new dhtmlXGridObject('gridbox');
    mygrid.setImagePath("images/dhtmlx/imgs/");
    mygrid.setHeader("ID,Full Name,Name with Initial,NIC,Institute,Section,Email,Status");
    mygrid.setInitWidths("30,200,200,100,200,200,200,75");
    mygrid.setColAlign("left,left,left,left,left,left,left,left");
    mygrid.setColSorting("server,server,server,server,server,na,na,na");
    mygrid.setColTypes("ro,ro,ro,ro,ro,ro,ro,ro");
    if (mygrid.setColspan){
       mygrid.attachEvent("onBeforeSorting", customColumnSort);
    }   
    mygrid.setSkin("dhx_skyblue");
    mygrid.enablePaging(true,10, 10, "pagingArea", true, "infoArea");
    mygrid.setPagingSkin("toolbar", "dhx_skyblue");
    mygrid.init();
    mygrid.attachEvent("onBeforePageChanged", function() {
        if (!this.getRowsNum()){
            return false;
        }
        return true;
    });
    mygrid.sortField_old = mygrid.sortField;
    mygrid.sortField = function() {
        mygrid.setColSorting("str,str,str,str,str,str,str,str");
        if (customColumnSort(arguments[0]))
        mygrid.sortField_old.apply(this, arguments);
    }
    //mygrid.setColumnHidden(0,true);
   // mygrid.setColumnHidden(3,true);
    mygrid.sortRows = function(col, type, order) {}
    mygrid.attachEvent("onRowSelect",doOnRowSelected);
    mygrid.attachEvent("onXLE", showLoading);
    mygrid.attachEvent("onXLS", function() {
        showLoading(true)
    });    
    mygrid.loadXML("?employee/gridEmploy&un=" + Date.parse(new Date()),function(){
      var myToolbar=mygrid.aToolBar;
        //myToolbar.setSkin("dhx_black");
        
   });
}

function showLoading(fl) {
    var span = document.getElementById("recfound");
    if (!span)
        return;
    if (!mygrid._serialise) {
        span.innerHTML = "<i>Loading... available in Professional Edition of dhtmlxGrid</i>";
        return;
    }
    span.style.color = "red";
    if (fl === true)
    span.innerHTML = "loading...";
    else
    span.innerHTML = "";
}

function doSearch(ev) {
    if (!flAuto)
    return;
    var elem = ev.target || ev.srcElement;
    if (timeoutHnd)
    clearTimeout(timeoutHnd);
    timeoutHnd = setTimeout(reloadGrid, 500);
}
function reloadGrid() {
    var searchCriteriaInstitute = document.getElementById("searchCriteria.institute").value;
    var searchCriteriaName = document.getElementById("searchCriteria.name").value;
    var searchCriteriaNic = document.getElementById("searchCriteria.nic").value;
    showLoading(true);
    mygrid.clearAndLoad("?employee/gridEmploy&name=" + searchCriteriaName + "&institute=" + searchCriteriaInstitute + "&nic="+searchCriteriaNic+"&orderBy=" + window.s_col + "&direction=" + window.a_direction);
    if (window.a_direction)
    mygrid.setSortImgState(true, window.s_col, window.a_direction);
}
function enableAutosubmit(state) {
    flAuto = state;
    document.getElementById("submitButton").disabled = state;
}

function customColumnSort(ind) {
    if (ind == 1) {
        window.s_col = 0;
        // alert("Table can't be sorted by this column.");
       //if (window.s_col)
        mygrid.setSortImgState(true, 1, window.a_direction);
       // return false;
    }else{
          window.s_col = ind;
    }
    // window.s_col = ind;
    var a_state = mygrid.getSortingState();

    window.a_direction = ((a_state[1] == "des") ? "asc": "des");
    reloadGrid();
    return true;
}

function doOnRowSelected(rowID,celInd){
    clearForm("frmData");
    clearValidate();
    disableForm("frmData");
    var params =encodeURIComponent("employId") + "="+rowID;
    ajaxPost("?employee/getEmploy", params, function(data) {
			var response =JSON.parse(data);
			if (response.status==false) {
				return;
			}
            document.getElementById("id").value  = rowID;
            document.getElementById("fullName").value  =response.fields.full_name;
            document.getElementById("initName").value  = response.fields.init_name;
            document.getElementById("email").value  = response.fields.email;
            document.getElementById("nic").value  = response.fields.nic;
            //document.getElementById("gender").value  = response.fields.gender
             if(response.fields.gender==1){
                document.getElementById("gender1").checked = true;
            }else{
                 document.getElementById("gender").checked = true;
             }
           // document.getElementById("epfNo").value  = response.fields.epf_no;
            document.getElementById("birthday").value  = response.fields.birthday;
            //document.getElementById("section_id").select  =response.fields.section_id;
            $("#institute_id").val( response.fields.institute_id ).attr('selected',true);
             //Synchronization with the function...
            doChangeSection(response.fields.section_id);

            $("#category_id").val( response.fields.category_id ).attr('selected',true);
            document.getElementById("designation").value  = response.fields.designation;
            document.getElementById("phoneMobile").value  = response.fields.phone_mobile;
            document.getElementById("phoneHome").value  = response.fields.phone_home;
            document.getElementById("phoneOffice").value  = response.fields.phone_office;
            document.getElementById("streetAddress1").value  = response.fields.p_address_line1;
            document.getElementById("streetAddress2").value  = response.fields.p_address_line2;
            document.getElementById("city").value  = response.fields.p_address_line3;
            document.getElementById("tempStreetAddress1").value  = response.fields.t_address_line1;
            document.getElementById("tempStreetAddress2").value  = response.fields.t_address_line2;
            document.getElementById("tempCity").value  = response.fields.t_address_line3;
            var pic  = response.fields.picture_src;
            if(response.fields.status==1){
                document.getElementById("status").checked = true;
            }          
            handleDefaultButtons("gridclick");
		});
    $("#messagePanel").removeClass();
    $("#messagePanel").html("" ) ;
}
function clearButton(){
    $("#messagePanel").removeClass();
    $("#messagePanel").html("" ) ;
    initialize();
}
function initialize(fnAfterInit) {
    clearForm("frmData");
    clearValidate();
    disableForm("frmData");
    handleDefaultButtons("load");
    
}
function edit(){
    enableForm("frmData");
    handleDefaultButtons("edit");
    disableElement("institute_id");
    disableElement("section_id");
  // disableElement("category_id");
   // disableElement("nic");
    isEdit=true;
}
function add(){
    initialize();
    enableForm("frmData");
    isNew = true;
    setField("id", "");
    $("#section_id").find('option').remove().end();
    handleDefaultButtons("add");
      $("#messagePanel").removeClass();
    $("#messagePanel").html("" ) ;
}
function save(){
    validateNic(save2);

}
function save2(){

                if(validateName() & validateEmail()& validateSection()) {
                var params = serializeForm("frmData") ;
                ajaxPost("?employee/add", params, function(data) {
			var response ;
            try
                {
                    response =JSON.parse(data);
                     $("#messagePanel").removeClass();
                     $("#messagePanel").addClass(response.type);
                     $("#messagePanel").html(response.message ) ;
                    if (response.status==false) {
				return;
			}
                }
                catch(err)
                {

                    $("#messagePanel").removeClass();
                     $("#messagePanel").addClass('error');
                     $("#messagePanel").html(data ) ;
                }


            reloadGrid();
			initialize();
		});
    }
		else
			 {
             return
            };

    handleDefaultButtons("save");

}
function del(){
    var isDelete=confirm("Confirm to Delete '"+ document.getElementById("fullName").value + "'  User !");
    if(isDelete ) {
        var params = serializeForm("frmData") ;
        ajaxPost("?employee/delete", params, function(data) {
			var response =JSON.parse(data);
			if (response.status==false) {
				return;
			}
            $("#messagePanel").removeClass();
            $("#messagePanel").addClass(response.type);
            $("#messagePanel").html(response.message ) ;
            reloadGrid();
			initialize();
		});
    }
		else
			return false;
    handleDefaultButtons("delete");
}
function doChangeSection(para){
    $("#section_id").find('option').remove().end();
    var params =encodeURIComponent("instituteId") + "="+document.getElementById("institute_id").value;
    ajaxPost("?employee/getSectionList", params, function(data) {
			var response =data;
			if (response.status==false) {
				return;
			}
                $('#section_id').append(response);
        $("#section_id").val( para).attr('selected',true);  
    });
}
function closePage(){
    window.location.href="?home";
}

function onLoad(){
     initialize();
     gridGenerator();
     enforcePrivileges();
    _birthday = new dhtmlXCalendarObject(["birthday"]);
    _birthday.hideTime();
}

onLoad();